package com.yanwq.sayhi.controller.audio;

import android.media.MediaRecorder;

import java.io.File;
import java.io.IOException;

/**
 * 作者：yanweiqiang。
 * 日期：2016/2/16 9:10。
 */
public class AudioRecorderWrap {
    private MediaRecorder mRecorder;
    private File mFile;

    public AudioRecorderWrap(File file) {
        mFile = file;

        try {
            if (file.exists()) {
                if (!file.delete()) {
                    return;
                }
            }

            if (!file.createNewFile()) {
                return;
            }

            mRecorder = new MediaRecorder();
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
            mRecorder.setOutputFile(file.getAbsolutePath());
            mRecorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void record() {
        try {

            if (mFile.exists()) {
                if (!mFile.delete()) {
                    return;
                }
            }

            if (!mFile.createNewFile()) {
                return;
            }

            mRecorder.reset();
            mRecorder = new MediaRecorder();
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
            mRecorder.setOutputFile(mFile.getAbsolutePath());
            mRecorder.prepare();
            mRecorder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void stop() {
        try {
            mRecorder.stop();
        } catch (RuntimeException ignore) {
        }
    }

    public void release() {
        mRecorder.release();
    }
}